/**
 * create by young (young2f@outlook.com) on 2020/8/24
 */


'use strict';
import React, {Component} from 'react';
import {Button, Form, Input, Table} from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import {FormField, ModalFooter, SearchForm} from 'antd-extra';
import notify from '../../components/NotificationExtra';

const _ = require('lodash');
moment.locale('zh-cn');

@Form.create()
export default class ModalSelectUser extends Component {
  constructor(props) {
    super(props);
    this.state = {users: [], loading: true, selectedRowKeys: []};
  }

  componentDidMount() {
    this.setState({user: [], loading: true});
    this.onLoadData().then(result => {
      result.loading = false;
      this.setState(result);
    });
  }

  async onLoadData() {
    const {current = 1, pageSize = 10} = this.state;
    let data = this.props.form.getFieldsValue();
    let {username, nickname} = data;
    /**
     * 输入框清除之后会成为 ”“
     * @type {undefined}
     */
    username = username === '' ? undefined : username;
    nickname = nickname === '' ? undefined : nickname;
    const payload = {
      nickname,
      username,
      skip: (current - 1) * pageSize,
      limit: pageSize
    };
    const res = await this.props.dispatch({
      type: 'user/findUsersByPage',
      payload,
    });
    console.log('用户列表', res);
    return res && res.result ? res.result : {};
  };

  renderFoot = () => {
    const {foot, value, result, modalRef, type} = this.props;
    const {selectedRowKeys, users = []} = this.state;
    if (foot) {
      return foot(value, modalRef);
    } else {

      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            if (!selectedRowKeys.length) {
              notify({type: 'error', message: '未选择设备！'});
              return;
            }
            const selected = [];
            for (let username of selectedRowKeys) {
              const user = _.find(users, item => {
                return item.username === username;
              });
              // const {organizations} = user;
              // let name = '';
              // _.map(organizations, org => {
              //   const {organizationName} = org;
              //   name += `${organizationName}、`;
              // });
              // user.organizationName = name;
              selected.push(user);
            }
            type === 'radio' ? result(selected[0]) : result(selected);
            modalRef.close();
          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };

  onSelectChange = selectedRowKeys => {
    this.setState({selectedRowKeys});
  };

  columns = () => {
    return [
      {title: '姓名', dataIndex: 'nickname'},
      {title: '账号', dataIndex: 'username'},
      {title: '角色', dataIndex: 'roleName'},
    ];
  };
  getSearchFields = () => {
    const arr = [
      <FormField
        label="姓名"
        name="nickname"
        key={1}
      >
        <Input allowClear placeholder="请输入人员姓名"/>
      </FormField>,
      <FormField
        label="用户账号"
        name="username"
        key={2}
      >
        <Input allowClear placeholder="请输入用户账号"/>
      </FormField>,
    ];
    return arr;
  };

  render() {
    const {selectedRowKeys, users = [], current = 1, loading, total = 0} = this.state;
    const {form, selectedUsers = [], type = 'checkbox'} = this.props;
    console.log('selected userss', selectedUsers);
    const rowSelection = {
      type,
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: record => ({
        disabled: _.find(selectedUsers, item => {
          return item.userCode === record.userCode;
        })
      })
    };
    const onSelectRow = (record) => {
      const {username} = record;
      const temp = _.find(selectedRowKeys, item => {
        return item === username;
      });
      if (temp) {
        _.remove(selectedRowKeys, item => item === username);
      } else {
        selectedRowKeys.push(record.username);
      }
      this.onSelectChange(selectedRowKeys);
    };

    return (<div>
      <SearchForm
        style={{marginLeft: '6px', marginRight: '6px'}}
        onSearch={() => {
          this.state.current = 1;
          this.componentDidMount();
        }}
        onReset={this.handleReset}
        cols={3}
        min={6}
        expandText="展开"
        form={form}
      >
        {this.getSearchFields()}
      </SearchForm>
      <Table
        className={'antTable'}
        bordered
        rowSelection={rowSelection}
        loading={loading}
        rowKey={record => record.username}
        columns={this.columns()}
        dataSource={users}
        onRow={(record) => ({
          onClick: () => onSelectRow(record)
        })}
        pagination={{
          current: current,
          total: total,
          showSizeChanger: true,
          onChange: page => {
            // this.setState({current:page})
            this.state.current = page;
            this.componentDidMount();
          },
          onShowSizeChange: (current, pageSize) => {
            this.state.current = 1;
            this.state.pageSize = pageSize;
            this.componentDidMount();
          }
        }}
      >
      </Table>
      {this.renderFoot()}
    </div>);
  }
}
